#include "../source/Server.hpp"

//未来服务器模块管理连接的结构
std::unordered_map<uint64_t,PtrConnect> _conns;  
uint64_t conn_id = 0;
EventLoop base_loop;
LoopThreadPool* loops;

int next_loop = 0;
void Destroy(const PtrConnect&conn){
    _conns.erase(conn->Id());
}
void Connected(const PtrConnect&conn){
    //获取原生指针的地址
    DBG_LOG("create connection: %p",conn.get());
}
void Message(const PtrConnect&conn,Buffer*buff){
    DBG_LOG("read message : %s",buff->ReadPositoin());
    buff->ReadMoveOffset(buff->ReadAbleSize());
    std::string str = "hello world";
    conn->Send(str.c_str(),str.size());
}

void NewConnection(int newfd){

    conn_id++;
    PtrConnect con(new Connection(loops->NextLoop(),conn_id,newfd));
    con->SetConnectedCallback(std::bind(Connected,std::placeholders::_1));
    con->SetMessageCallBack(std::bind(Message,std::placeholders::_1,std::placeholders::_2));
    con->SetSrvClosedCallBack(std::bind(Destroy,std::placeholders::_1));
    con->EnabelInactiveRelease(10);
    con->Established(); //修改状态，启动读事件
    _conns.insert(std::make_pair(conn_id,con));
}

int main()
{
    loops = new LoopThreadPool(&base_loop);
    loops->SetLoopThreadCount(2);
    loops->CreateLoopThreadPool();
    Acceptor acceptor(&base_loop,8080);
    acceptor.SetAcceptorCallBack(std::bind(NewConnection,std::placeholders::_1));
    acceptor.Listen();
    base_loop.Start();

    return 0;
}